package com.rc.saas.tenant.service.member;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.common.utils.RandomValueUtil;
import com.rc.saas.tenant.common.utils.StringUtil;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.mapper.enterprise.EnterpriseMemberMapper;
import com.rc.saas.tenant.mapper.enterprise.EnterpriseSubmemberMapper;
import com.rc.saas.tenant.mapper.member.MemberAccountMapper;
import com.rc.saas.tenant.mapper.member.MemberAccountRecordMapper;
import com.rc.saas.tenant.mapper.member.MemberInfoMapper;
import com.rc.saas.tenant.mapper.member.RcMemberFlagMapper;
import com.rc.saas.tenant.mapper.tenant.TenantMapper;
import com.rc.saas.tenant.model.enterprise.EnterpriseMember;
import com.rc.saas.tenant.model.enterprise.EnterpriseSubmember;
import com.rc.saas.tenant.model.enterprise.EnterpriseSubmemberExample;
import com.rc.saas.tenant.model.member.*;
import com.rc.saas.tenant.model.tenant.Tenant;
import com.rc.saas.tenant.search.member.MemberSearch;
import com.rc.saas.tenant.service.member.gain.RcMemberGainRecordService;
import com.rc.saas.tenant.vo.member.MemberInfoPrintVo;
import com.rc.saas.tenant.vo.member.MemberResultVo;
import io.jsonwebtoken.lang.Collections;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


/**
 * @author frog
 * @date 2019/11/20
 */
@Service
public class MemberInfoServiceImpl implements MemberInfoService {
    @Autowired
    private MemberInfoMapper memberInfoMapper;

    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private MemberAccountMapper memberAccountMapper;

    @Autowired
    private MemberAccountRecordMapper memberAccountRecordMapper;

    @Autowired
    private EnterpriseMemberMapper enterpriseMemberMapper;

    @Autowired
    private EnterpriseSubmemberMapper enterpriseSubmemberMapper;

    @Autowired
    private RcMemberGainRecordService memberGainRecordService;

    @Autowired
    private RcMemberFlagMapper memberFlagMapper;

    @Autowired
    private RcMemberGainSettingService memberGainSettingService;

    @Override
    public MemberInfoMapper getMapper() {
        return memberInfoMapper;
    }

    @Override
    public Long insertReturnId(MemberInfo memberInfo) {
        return memberInfoMapper.insertReturnId(memberInfo);
    }

    @Override
    public void updateStatus(Long memberId) {
        //状态(0正常 1停用) 默认 0
        MemberInfo memberInfo = memberInfoMapper.selectByPrimaryKey(memberId);
        //判断是否是主会员
        EnterpriseMember enterpriseMember = enterpriseMemberMapper.selectMemberByMemberId(memberId);
        //判断是否是子会员
        EnterpriseSubmember enterpriseSubmember = enterpriseSubmemberMapper.selectMemberByMemberId(memberId);
        if (enterpriseMember != null) {
            //如果是主会员，冻结该主会员，对应的子会员也要冻结
            EnterpriseSubmemberExample enterpriseSubmemberExample = new EnterpriseSubmemberExample();
            enterpriseSubmemberExample.createCriteria().andBelongEnterpriseIdEqualTo(enterpriseMember.getEnterpriseId());
            List<EnterpriseSubmember> enterpriseSubmembers = enterpriseSubmemberMapper.selectByExample(enterpriseSubmemberExample);
            if (!CollectionUtils.isEmpty(enterpriseSubmembers)) {
                for (EnterpriseSubmember enterpriseSubmember1 : enterpriseSubmembers) {
                    if ("0".equals(enterpriseSubmember1.getStatus())) {
                        enterpriseSubmember1.setStatus("2");
                    } else if ("2".equals(enterpriseSubmember1.getStatus())) {
                        enterpriseSubmember1.setStatus("0");
                    }
                    enterpriseSubmemberMapper.updateByPrimaryKeySelective(enterpriseSubmember1);
                }
            }
            if ("0".equals(enterpriseMember.getStatus())) {
                enterpriseMember.setStatus("1");
            } else if ("1".equals(enterpriseMember.getStatus())) {
                enterpriseMember.setStatus("0");
            }
            enterpriseMemberMapper.updateByPrimaryKey(enterpriseMember);
        }
        if (enterpriseSubmember != null) {
            if ("0".equals(enterpriseSubmember.getStatus())) {
                enterpriseSubmember.setStatus("2");
            } else if ("2".equals(enterpriseSubmember.getStatus())) {
                enterpriseSubmember.setStatus("0");
            }
            enterpriseSubmemberMapper.updateByPrimaryKeySelective(enterpriseSubmember);
        }
        if ("1".equals(memberInfo.getStatus())) {
            memberInfo.setStatus("0");
        } else if ("0".equals(memberInfo.getStatus())) {
            memberInfo.setStatus("1");
        }
        memberInfoMapper.updateByPrimaryKeySelective(memberInfo);
    }

    @Override
    public MemberInfo selectMemberByMobile(String tenantCode, String moblie) {
        MemberInfoExample example = new MemberInfoExample();
        if (StringUtil.isBlank(moblie)) {
            return null;
        }
        example.createCriteria().andTenantCodeEqualTo(tenantCode).andMobileEqualTo(moblie);
        List<MemberInfo> memberInfos = memberInfoMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(memberInfos)) {
            return memberInfos.get(0);
        }
        return null;
    }


    @Override
    public long countAllMember(String tenantCode) {
        MemberInfoExample example = new MemberInfoExample();
        example.createCriteria().andTenantCodeEqualTo(tenantCode);
        long count = memberInfoMapper.countByExample(example);
        return count;
    }

    @Override
    public long countTodayNewAdd(String tenantCode) throws ParseException {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String today = format.format(date);
        StringBuilder begin = new StringBuilder(today);
        StringBuilder end = new StringBuilder(today);

        begin.append(" 00:00:00");
        end.append(" 23:59:59");

        SimpleDateFormat change = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date beginTime = change.parse(begin.toString());
        Date endTime = change.parse(end.toString());

        MemberInfoExample example = new MemberInfoExample();
        example.createCriteria().andTenantCodeEqualTo(tenantCode).andRegisterTimeLessThanOrEqualTo(endTime).andRegisterTimeGreaterThanOrEqualTo(beginTime);
        long count = memberInfoMapper.countByExample(example);
        return count;
    }

    @Override
    public MemberInfo selectMemberByOpenid(String openId) {
        MemberInfoExample example = new MemberInfoExample();
        example.createCriteria().andWechatOpenidEqualTo(openId);
        List<MemberInfo> members = memberInfoMapper.selectByExample(example);
        if (members != null && members.size() > 0) {
            return members.get(0);
        } else {
            return null;
        }
    }

    @Override
    public MemberInfo selectMemberByUnionidTenantCode(String unionid, String tenantCode) {
        MemberInfoExample example = new MemberInfoExample();
        example.createCriteria().andWechatUnionidEqualTo(unionid).andTenantCodeEqualTo(tenantCode);
        List<MemberInfo> members = memberInfoMapper.selectByExample(example);
        if (members != null && members.size() > 0) {
            return members.get(0);
        } else {
            return null;
        }
    }

    @Override
    public List<MemberInfoPrintVo> exportMemberInfo(MemberSearch memberSearch) {
        return memberInfoMapper.exportMemberInfo(memberSearch);
    }

    @Override
    public PageInfo<MemberResultVo> listPageMember(MemberSearch search) {
        List<Long> memberIds = JSONObject.parseArray(search.getSelectRows(), Long.class);
        if (!Collections.isEmpty(memberIds)) {
            search.setMemberIds(memberIds);
        } else {
            PageHelper.startPage(search.getOffset(), search.getLimit());
        }

        List<MemberResultVo> list = memberInfoMapper.listMember(search);
        list.forEach(memberResultVo -> {
//            List<RcMemberGainRecord> memberGainRecordList = memberGainRecordService.listMemberGain(memberResultVo.getMemberId());
            List<RcMemberGainSetting> gainSettingList = memberGainSettingService.listAvailableMemberGain(memberResultVo.getSubLevel());

            String gain = null;
            //列出会员所拥有的权益
            if (!CollectionUtils.isEmpty(gainSettingList)) {
                String consumeGain = "";
                String donateGain = "";
                String birthGain = "";
                for (RcMemberGainSetting gainSetting : gainSettingList) {
                    if (StringUtils.isEmpty(consumeGain) && "0".equals(gainSetting.getGainType())) {
                        consumeGain = "充值消费折扣;";

                    } else if (StringUtils.isEmpty(consumeGain) && "1".equals(gainSetting.getGainType())) {
                        donateGain = "充值赠送金额;";
                    } else {
                        birthGain = "生日礼遇;";
                    }
                }
                gain = consumeGain + donateGain + birthGain;
            }


            RcMemberFlag memberFlag = memberFlagMapper.selectByPrimaryKey(memberResultVo.getMemberId());
            if(memberFlag!=null){
                memberResultVo.setMemberLevel(memberFlag.getMemberLevel());
                memberResultVo.setIsMemberLevel(memberFlag.getIsMemberLevel());
            }
//            memberResultVo.setMemberGainRecords(memberGainRecordList);
            memberResultVo.setGain(gain);

        });

        return new PageInfo<>(list);
    }


    @Override
    public MemberResultVo selectMemberAndAccountByMobile(String tenantCode, String mobile) {
        return memberInfoMapper.selectMemberAndAccountByMobile(tenantCode, mobile);
    }

    @Override
    public String registerRandomMobile(String tenantCode, int memberNum) {
        String mobiles = "";
        for (int i = 0; i < memberNum; i++) {
            //生成会员
            MemberInfo member = new MemberInfo();
            Date date = new Date();
            //member.setWechatOpenid(openid);
            //生成随机手机号码与名称,防止重复手机号码出现
            for (int j = 0; j < 100; j++) {
                member.setMobile(RandomValueUtil.getTel());
                MemberInfo memberInfo = this.selectMemberByMobile(tenantCode, member.getMobile());
                if (memberInfo == null) {
                    break;
                }
            }

            member.setNickname2(RandomValueUtil.getChineseName());
            //member.setWechatUnionid(unionid);
            member.setTenantCode(tenantCode);
            member.setRegisterTime(date);
            member.setCreatedTime(date);
            //后台随机生成
            member.setMemberSource("3");

            //性别(0未确定 1男 2女) 默认0
            member.setSex("0");

            //会员类型(0个人 1企业 2互联互通用户) 默认0
            member.setMemberType("0");

            //(elec_status)用户是否在充电 0不是，1正充电 默认0
            member.setChargeStatus("0");

            //(elec_type)充电类型 0单冲  1多充 默认0
            member.setChargeType("0");

            //状态(0正常 1停用) 默认 0
            member.setStatus("0");
            //新增会员
            memberInfoMapper.insertReturnId(member);
            mobiles = mobiles + member.getMobile() + ",";

            Tenant tenant = tenantMapper.selectByPrimaryKey(member.getTenantCode());

            //注册赠送金额
            if (tenant.getRegisteGiveAmount().doubleValue() > 0) {
                MemberAccountRecord memberAccountRecord = new MemberAccountRecord();
                memberAccountRecord.setTenantCode(member.getTenantCode());
                memberAccountRecord.setMemberId(member.getMemberId());
                memberAccountRecord.setAccountType("0");
                memberAccountRecord.setRecordType("5");
                memberAccountRecord.setAmount(tenant.getRegisteGiveAmount());
                memberAccountRecord.setResult(tenant.getRegisteGiveAmount());
                memberAccountRecord.setCreatedTime(member.getCreatedTime());
                memberAccountRecord.setRemark("注册平台赠送");
                memberAccountRecord.setLastUpdatedTime(new Date());
                memberAccountRecord.setCreatedTime(new Date());
                memberAccountRecordMapper.insertSelective(memberAccountRecord);
                //member_account
                MemberAccount memberAccount = new MemberAccount();
                memberAccount.setAccount(tenant.getRegisteGiveAmount());
                memberAccount.setMemberId(member.getMemberId());
                memberAccount.setTenantCode(member.getTenantCode());
                memberAccount.setAccount(BigDecimal.ZERO);
                memberAccount.setGiveAccount(BigDecimal.ZERO);
                memberAccount.setEnterpriseAccount(BigDecimal.ZERO);
                memberAccount.setAllTransferAmount(BigDecimal.ZERO);
                memberAccount.setPoint(0);
                memberAccount.setCreatedTime(new Date());
                memberAccount.setLastUpdatedTime(new Date());
                memberAccountMapper.insertSelective(memberAccount);
            } else {
                //新增member_account
                MemberAccount memberAccount = new MemberAccount();
                memberAccount.setMemberId(member.getMemberId());
                memberAccount.setTenantCode(member.getTenantCode());
                memberAccount.setAccount(BigDecimal.ZERO);
                memberAccount.setGiveAccount(BigDecimal.ZERO);
                memberAccount.setEnterpriseAccount(BigDecimal.ZERO);
                memberAccount.setAllTransferAmount(BigDecimal.ZERO);
                memberAccount.setPoint(0);
                memberAccount.setCreatedTime(new Date());
                memberAccount.setLastUpdatedTime(new Date());
                memberAccountMapper.insertSelective(memberAccount);
            }
        }
        return mobiles.substring(0, mobiles.length() - 1);
    }

    @Override
    public TResponse registerMemberRetId(String tenantCode) {

        //生成会员
        MemberInfo member = new MemberInfo();
        Date date = new Date();
        //member.setWechatOpenid(openid);
        //生成随机手机号码与名称,防止重复手机号码出现

        member.setMobile(RandomValueUtil.getTel());
        MemberInfo memberInfo = this.selectMemberByMobile(tenantCode, member.getMobile());
        if (memberInfo == null) {
            TResponse.FAIL("请重新生成");
        }


        member.setNickname2(RandomValueUtil.getChineseName());
        //member.setWechatUnionid(unionid);
        member.setTenantCode(tenantCode);
        member.setRegisterTime(date);
        member.setCreatedTime(date);
        //后台随机生成
        member.setMemberSource("3");

        //性别(0未确定 1男 2女) 默认0
        member.setSex("0");

        //会员类型(0个人 1企业 2互联互通用户) 默认0
        member.setMemberType("0");

        //(elec_status)用户是否在充电 0不是，1正充电 默认0
        member.setChargeStatus("0");

        //(elec_type)充电类型 0单冲  1多充 默认0
        member.setChargeType("0");

        //状态(0正常 1停用) 默认 0
        member.setStatus("0");
        //新增会员
        memberInfoMapper.insertReturnId(member);

        Tenant tenant = tenantMapper.selectByPrimaryKey(member.getTenantCode());

        //注册赠送金额
        if (tenant.getRegisteGiveAmount().doubleValue() > 0) {
            MemberAccountRecord memberAccountRecord = new MemberAccountRecord();
            memberAccountRecord.setTenantCode(member.getTenantCode());
            memberAccountRecord.setMemberId(member.getMemberId());
            memberAccountRecord.setAccountType("0");
            memberAccountRecord.setRecordType("5");
            memberAccountRecord.setAmount(tenant.getRegisteGiveAmount());
            memberAccountRecord.setResult(tenant.getRegisteGiveAmount());
            memberAccountRecord.setCreatedTime(member.getCreatedTime());
            memberAccountRecord.setRemark("注册平台赠送");
            memberAccountRecord.setLastUpdatedTime(new Date());
            memberAccountRecord.setCreatedTime(new Date());
            memberAccountRecordMapper.insertSelective(memberAccountRecord);
            //member_account
            MemberAccount memberAccount = new MemberAccount();
            memberAccount.setAccount(tenant.getRegisteGiveAmount());
            memberAccount.setMemberId(member.getMemberId());
            memberAccount.setTenantCode(member.getTenantCode());
            memberAccount.setAccount(BigDecimal.ZERO);
            memberAccount.setGiveAccount(BigDecimal.ZERO);
            memberAccount.setEnterpriseAccount(BigDecimal.ZERO);
            memberAccount.setAllTransferAmount(BigDecimal.ZERO);
            memberAccount.setPoint(0);
            memberAccount.setCreatedTime(new Date());
            memberAccount.setLastUpdatedTime(new Date());
            memberAccountMapper.insertSelective(memberAccount);
        } else {
            //新增member_account
            MemberAccount memberAccount = new MemberAccount();
            memberAccount.setMemberId(member.getMemberId());
            memberAccount.setTenantCode(member.getTenantCode());
            memberAccount.setAccount(BigDecimal.ZERO);
            memberAccount.setGiveAccount(BigDecimal.ZERO);
            memberAccount.setEnterpriseAccount(BigDecimal.ZERO);
            memberAccount.setAllTransferAmount(BigDecimal.ZERO);
            memberAccount.setPoint(0);
            memberAccount.setCreatedTime(new Date());
            memberAccount.setLastUpdatedTime(new Date());
            memberAccountMapper.insertSelective(memberAccount);
        }

        return TResponse.SUCCESS_DATA(member.getMemberId());
    }

    @Override
    public MemberResultVo selectMemberById(Long memberId) {
        MemberResultVo resultVo = memberInfoMapper.selectMemberById(memberId);
        RcMemberFlag memberFlag = memberFlagMapper.selectByPrimaryKey(memberId);
        resultVo.setMemberLevel(memberFlag.getMemberLevel());
        resultVo.setIsMemberLevel(memberFlag.getIsMemberLevel());
        return resultVo;
    }
}
